from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView
from rest_framework import permissions
from rest_framework import viewsets
from rest_framework import filters

from rest_framework.views import APIView
# from captcha.views import CaptchaStore, captcha_image

from django_filters import rest_framework
from django.http import Http404
from django.http import HttpResponse

from ..models import Article,User,FileUpload
from ..serializer.serializers2 import ArticleSerializer,UserSerializer,FileUploadSerializer
from ..permissions import IsOwnerOrReadOnly,IsOwner
from ..pagination import MyPageNumberPagination
from ..filters import ArticleFilter

class ArticleViewSet(viewsets.ModelViewSet):
    # 用一个视图集替代ArticleList和ArticleDetail两个视图
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    # permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    # permission_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly)
    # authentication_classes = (SessionAuthentication, BasicAuthentication)
    # permission_classes = [IsOwner]
    pagination_class=MyPageNumberPagination

     # new: filter backends and classes
    #  http://127.0.0.1:8000/v1/articles/?page=1&size=10&q=django&status=
    # filter_backends = (rest_framework.DjangoFilterBackend,)
    # filterset_class  = ArticleFilter  #注意不是filter_class 

    # new: add SearchFilter and search_fields
    #http://127.0.0.1:8000/v1/articles/?page=1&size=10&search=django&status=p
    filter_backends = (filters.SearchFilter, filters.OrderingFilter,)
    # search_fields = ('title',)
    search_fields = ('title', 'author__username')
    ordering_fields = ('create_date',)

    #自定义过滤
    # def get_queryset(self):
    #     keyword = self.request.query_params.get('q')
    #     if not keyword:
    #         queryset = Article.objects.all()
    #     else:
    #         queryset = Article.objects.filter(title__icontains=keyword)
    #     return queryset

    # 自行添加，将request.user与author绑定
    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

    # 自行添加，将request.user与author绑定
    def perform_update(self, serializer):
        serializer.save(author=self.request.user)

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    # pagination_class=MyPageNumberPagination
    # permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    # permission_classes = (permissions.IsAuthenticated,)
    # permission_classes=(permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly)

# 链接：https://juejin.cn/post/6993977104299720741
# class CaptchaAPIView(APIView):
    
#     def get(self, request):
#         hashkey = CaptchaStore.generate_key()
#         try:
#             #获取图片id
#             id_ = CaptchaStore.objects.filter(hashkey=hashkey).first().id
#             imgage = captcha_image(request, hashkey)
#             #将图片转换为base64
#             image_base = 'data:image/png;base64,%s' % base64.b64encode(imgage.content).decode('utf-8')
#             json_data = json.dumps({"id": id_, "image_base": image_base })
#             # 批量删除过期验证码
#             CaptchaStore.remove_expired()
#         except:
#             json_data = None
#         return HttpResponse(json_data, content_type="application/json") 

class FileUploadViewSet(viewsets.ModelViewSet):
    queryset = FileUpload.objects.all()
    serializer_class = FileUploadSerializer

    filter_backends = (filters.SearchFilter, filters.OrderingFilter,)
    # search_fields = ('title',)
    search_fields = ('upname', 'author__username')
    ordering_fields = ('create_date',)

     # 自行添加，将request.user与author绑定
    def perform_create(self, serializer):
        serializer.save(author=self.request.user)